package fm.dongman.animefm.view.widget

import android.animation.ValueAnimator
import android.content.Context
import android.graphics.Color
import android.support.v4.content.ContextCompat
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.AccelerateDecelerateInterpolator
import android.widget.FrameLayout
import android.widget.TextView
import fm.dongman.animefm.R
import fm.dongman.animefm.contractlib.model.ClassifyDataModel
import org.jetbrains.anko.enabled
import org.jetbrains.anko.onClick
import org.jetbrains.anko.textColor

/**
 * 分类器控件
 * Created by shize on 2017/10/24.
 */
class ClassifyView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0)
    : FrameLayout(context, attrs, defStyleAttr) {
    companion object {
        val DEFAULT_SPAN = 4 // 默认分类列表列数
        val DEFAULT_DURATION = 300 // 默认动画时间
        val DEFAULT_TITLE_SELECT_BG = android.R.color.darker_gray // 默认标题选中背景
        val DEFAULT_CONTENT_SELECT_BG = android.R.color.darker_gray // 默认内容选中背景

        var mTitleSelectBackgroundResId: Int = DEFAULT_TITLE_SELECT_BG // 标题选中背景
        var mContentSelectBackgroundResId: Int = DEFAULT_CONTENT_SELECT_BG // 内容选中背景
    }

    private lateinit var mLayout: View // 布局 view
    private var mTypes: List<String> = ArrayList() // 分类集合
    private var mAdapters: List<ComicClassifyAdapter> = ArrayList() // 适配器集合

    private lateinit var mTypeRecycler: RecyclerView // 分类列表
    private lateinit var mContentBackgroundView: View // 类型列表背景
    private lateinit var mContentRecycler: RecyclerView // 类型列表
    private var mTypeAdapter: ClassifyViewTypeAdapter? = null // 分类适配器

    private var mTypeTv: TextView? = null // 当前点击的类型标题
    private var mTypePos: Int = 0 // 当前点击的分类项

    var mSpanType: Int = DEFAULT_SPAN // 分类列表列数
    var mAnimatorDuration: Long = DEFAULT_DURATION.toLong() // 动画时间

    init {
        val ta = context.obtainStyledAttributes(attrs, R.styleable.ClassifyView)
        if (ta != null) {
            mSpanType = ta.getInt(R.styleable.ClassifyView_contentSpan, DEFAULT_SPAN)
            mAnimatorDuration = ta.getInt(R.styleable.ClassifyView_contentAnimatorDuration, DEFAULT_DURATION).toLong()
            mTitleSelectBackgroundResId = ta.getResourceId(R.styleable.ClassifyView_titleSelectBackground, DEFAULT_TITLE_SELECT_BG)
            mContentSelectBackgroundResId = ta.getResourceId(R.styleable.ClassifyView_contentSelectBackground, DEFAULT_CONTENT_SELECT_BG)
            ta.recycle()
        }
    }

    override fun onFinishInflate() {
        super.onFinishInflate()
        mLayout = LayoutInflater.from(context).inflate(R.layout.view_classify, null)
    }

    /**
     * 设置分类以及对应分类的适配器
     * @param types 类型集合
     * @param adapters 适配器集合
     */
    fun setDataSource(types: List<String>, adapters: List<ComicClassifyAdapter>) {
        mTypes = types
        mAdapters = adapters
        showContent()
    }

    /**
     * 设置类型文本
     * @param txt 文本
     */
    fun setTypeText(txt: String) {
        mTypeTv?.text = txt
        showListVisibility()
    }

    /**
     * 显示内容
     */
    private fun showContent() {
        // 设置分类列表
        setTypeRecycler()
        // 设置类型列表
        setClassifyRecycler()
        // 设置隐藏类型列表
        setClassifyListBackground()
        // 添加 view 到容器
        addView(mLayout)
    }

    /**
     * 设置类型列表背景
     */
    private fun setClassifyListBackground() {
        mContentBackgroundView = mLayout.findViewById(R.id.mComicsLayout)
        mContentBackgroundView.onClick {
            showListVisibility()
        }
        mContentBackgroundView.visibility = View.GONE
    }

    /**
     * 设置类型列表
     */
    private fun setClassifyRecycler() {
        mContentRecycler = mLayout.findViewById(R.id.mComics) as RecyclerView
        mContentRecycler.layoutManager = GridLayoutManager(context, mSpanType, GridLayoutManager.VERTICAL, false)
    }

    /**
     * 设置分类列表
     */
    private fun setTypeRecycler() {
        mTypeRecycler = mLayout.findViewById(R.id.mClassify) as RecyclerView
        mTypeRecycler.layoutManager = GridLayoutManager(context,mTypes.size,GridLayoutManager.VERTICAL, false)
        mTypeAdapter = ClassifyViewTypeAdapter(context, mTypes)
        mTypeAdapter!!.mItemClickListener = mTypeItemClickListener
        mTypeRecycler.adapter = mTypeAdapter
    }

    /**
     * 分类项点击事件
     */
    private val mTypeItemClickListener: OnTypeItemClickListener = object : OnTypeItemClickListener {
        override fun onTypeClick(view: View, position: Int) {
            mTypeTv = view as TextView // 获取当前点击的类型标题 TextView
            mTypePos = position
            // 分类项目点击事件
            if (mContentBackgroundView.visibility == View.VISIBLE) {
                // 当前处于显示状态
                showListVisibility()
            } else {
                // 当前处于隐藏状态
                showListGone()
            }
        }
    }

    /**
     * 显示列表隐藏状态下的分类点击事件
     */
    private fun showListGone() {
        if (mContentRecycler.adapter != mAdapters[mTypePos]) {
            mContentRecycler.adapter = mAdapters[mTypePos]
        }
        doAnimation(0f, 1f)
    }

    /**
     * 显示列表显示状态下的分类点击事件
     */
    private fun showListVisibility() {
        if (mContentRecycler.adapter != mAdapters[mTypePos]) {
            // 防止重复点击
            mContentRecycler.adapter = mAdapters[mTypePos]
            return
        }
        doAnimation(1f, 0f)
    }

    /**
     * 添加动画
     * @param from 起始值
     * @param to 目标值
     */
    private fun doAnimation(from: Float, to: Float) {
        mTypeTv!!.enabled = false
        val animator = ValueAnimator.ofFloat(from, to)
        animator.interpolator = AccelerateDecelerateInterpolator()
        animator.duration = mAnimatorDuration
        animator.addUpdateListener {
            val value = it.animatedValue as Float
            mContentBackgroundView.alpha = value
            if (value == from && from == 0f) {
                // 第一次执行并判断当前为隐藏
                mContentBackgroundView.visibility = View.VISIBLE
            }

            if (value == to && to == 0f) {
                // 第一次执行并判断当前为显示
                mContentBackgroundView.visibility = View.GONE
                mTypeAdapter?.selectPosition(-1)
            }

            if (value == to) {
                // 防止重复点击显示错误
                mTypeTv!!.enabled = true
            }
        }
        animator.start()
    }

    /**
     * 分类项事件监听器
     */
    private interface OnTypeItemClickListener {
        fun onTypeClick(view: View, position: Int)
    }

    /**
     * 分类控件的类型适配器
     */
    private class ClassifyViewTypeAdapter constructor(private val mContext: Context, private val mData: List<String>)
        : RecyclerView.Adapter<TypeViewHolder>() {
        var mItemClickListener: OnTypeItemClickListener? = null // 项目点击事件
        private var mPosition: Int = -1 // 记录点击位置

        override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): TypeViewHolder =
                TypeViewHolder(LayoutInflater.from(mContext).inflate(R.layout.item_view_classify_type, parent, false))

        override fun onBindViewHolder(holder: TypeViewHolder?, position: Int) {
            // 只有第一次才加载数据
            if (holder!!.mTextView.text == mContext.getString(R.string.app_name)) {
                holder.mTextView.text = mData[position]
            }
            // 设置点击事件
            holder.mTextView.onClick {
                mItemClickListener?.onTypeClick(it!!, position)
                selectPosition(position)
            }
            // 记录选中状态
            holder.mTextView.background = null
            holder.mTextView.textColor = ContextCompat.getColor(mContext,R.color.secondary_text)

            if (mPosition == position) {
                holder.mTextView.background = mContext.getDrawable(mTitleSelectBackgroundResId)
                holder.mTextView.textColor = ContextCompat.getColor(mContext,android.R.color.white)
            }
        }

        override fun getItemCount(): Int = mData.size

        /**
         * 选中当前选项
         * @param position 选中位置 -1 为没有选中
         */
        fun selectPosition(position: Int) {
            if (mPosition == position) {
                mPosition = -1
            } else {
                mPosition = position
            }
            notifyDataSetChanged()
        }
    }

    /**
     * 分类列表 ViewHolder
     */
    private class TypeViewHolder constructor(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val mTextView: TextView = itemView.findViewById(R.id.mClassifyText) as TextView
    }

    /**
     * 类型列表事件监听器
     */
    interface OnItemClickListener {
        /**
         * 点击 item 事件监听
         * @param key item 的 title
         */
        fun onClick(key: ClassifyDataModel.TypeData)
    }

    /**
     * 类型列表适配器
     */
    class ComicClassifyAdapter constructor(private val mContext: Context, private val mData: List<ClassifyDataModel.TypeData>)
        : RecyclerView.Adapter<ClassifyViewHolder>() {
        private var mListener: OnItemClickListener? = null
        private var mPosition: Int = 0 // 记录点击位置

        override fun getItemCount(): Int = mData.size

        override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): ClassifyViewHolder =
                ClassifyViewHolder(LayoutInflater.from(mContext).inflate(R.layout.item_view_classify, parent, false))

        override fun onBindViewHolder(holder: ClassifyViewHolder?, position: Int) {
            holder!!.mTextView.text = mData[position].name
            holder.mTextView.onClick {
                mPosition = position
                mListener?.onClick(mData[position])
                notifyDataSetChanged()
            }
            holder.mTextView.background = null
            if (mPosition == position) {
                holder.mTextView.background = mContext.getDrawable(mContentSelectBackgroundResId)
            }
        }

        /**
         * 设置点击事件
         */
        fun setOnItemClickListener(listener: OnItemClickListener) {
            mListener = listener
        }
    }

    /**
     * 类型列表 ViewHolder
     */
    class ClassifyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val mTextView: TextView = itemView.findViewById(R.id.mClassifyTypeText) as TextView
    }
}